#include "stdafx.h"

#include "volume_map.hpp"
#include <sstream>
#include <fstream>
#include <algorithm>
#include <boost/algorithm/string.hpp>

const char volume_map::DELIMITER = ',';
const char volume_map::COMMENT = '#';

bool volume_map::parse(const char *filename)
{
	std::string line;
	char letter;
	bool status(false);

	std::pair<std::map< char, std::string >::iterator, bool> str_res;
	
	std::ifstream input_file(filename);
	if (input_file.is_open())
	{
		while ( input_file.good() )
		{
			std::getline (input_file,line);

			line = boost::trim_left_copy(line);
			if(line[0] == COMMENT) continue;

			std::string directive = line.substr(0, line.find_first_of(DELIMITER));
			//directive.erase(std::remove_if(directive.begin(), directive.end(), isspace), directive.end());
			boost::trim(directive);
			boost::algorithm::to_upper<std::string>(directive);
			letter = directive[0];
			
			line = line.substr(line.find_first_of(DELIMITER)+1, line.length()); // extract remaining string, as volume label
			boost::trim(line);
			
			boost::algorithm::to_upper(line);
			str_res = _volume_map.insert(std::make_pair(letter, line));																					
//				std::cout << "command = " << line << std::endl;
		}
	}

	input_file.close();

	return status;
}



bool volume_map::init_from(std::string const& _filename)
{
	if(parse(_filename.c_str()))
		if(!_volume_map.empty())
	{ return true;	}

	return  false;
}

volume_map::volume_map(std::string const& _filename)
{
	init_from(_filename);
}


bool volume_map::empty()
{
	return _volume_map.empty();
}



std::string const volume_map::get_label(char _id) const
{
	std::map <char, std::string >::const_iterator iterator = _volume_map.find(_id);
	if(iterator != _volume_map.end()) return iterator->second;

	return "";
}


std::ostream& operator << (std::ostream& ost, volume_map const& c)
{
	std::map < char, std::string >::const_iterator j = c._volume_map.begin();
	std::map < char, std::string >::const_iterator k = c._volume_map.end();

	for(; j != k; j++)
	{
		ost << j->first << ", " << j->second << std::endl;
	}

	return ost;
}

